import os
import json
import werkzeug
import datetime
import requests
from odoo import http, fields
from odoo.http import request, Response
from ...data_models.api_models import RPInterfaceModelForHeader as RPHeader
from ...data_models.api_models import RPInterfaceModelForResponse as RPResponse
from ..abstract_interface.common import APICommon
from ...data_models.api_models import RPInterfaceModelForGet as RP_Get
from ...tools.encapsulation import valid_response, invalid_business, invalid_response, invalid_request
from ...tools.decorator import validate_rp_api, exception_handler
from ...static import request_schema_json


class APICommonImplement(APICommon):

    @validate_rp_api(schema=request_schema_json.get_test, lang=True)
    @http.route(route='/api/test/http_get_test', type='http', auth='none', methods=['GET'], cors="*", csrf=False)
    def http_get_test(self, **kwargs):
        data = {
            'get': kwargs,
        }
        status = 200
        rp_header = RPHeader(len(data))  # 创建响应头模型
        rp_response = RPResponse(status)  # 创建响应response模型
        data = {'response': rp_response.printf(),
                'data': data}
        re = Response(json.dumps(data, ensure_ascii=False),
                      status=status,
                      headers=rp_header.printf())
        return re

    @validate_rp_api(schema=request_schema_json.get_test, lang=True)
    @http.route(route='/api/test/http_post_test', type='http', auth='none', methods=['POST'], cors="*", csrf=False)
    def http_post_test(self, **kwargs):
        data = {
            'post': kwargs,
        }
        status = 200
        rp_header = RPHeader(len(data))  # 创建响应头模型
        rp_response = RPResponse(status)  # 创建响应response模型
        data = {'response': rp_response.printf(),
                'data': data}
        re = Response(json.dumps(data, ensure_ascii=False),
                      status=status,
                      headers=rp_header.printf())
        return re

    @exception_handler
    @validate_rp_api(lang=True)
    @http.route(route='/api/common/get_package_type', auth='none', methods=['GET'], cors="*", csrf=False)
    def get_package_type(self, **kwargs):
        """ 获取包裹类型 """
        _language_code = request.lang
        package_type = request.env['rp.shipper.package'].with_context({'lang': _language_code}).sudo().search_read(domain=[],
                                                                                                                   fields=['id', 'name'],
                                                                                                                   order='en_name ASC')
        data = package_type
        return valid_response(data)

    @exception_handler
    @validate_rp_api(lang=True)
    @http.route(route='/api/common/get_country_list', auth='none', method=['GET'], cors="*", csrf=False)
    def get_country_list(self, **kwargs):
        """ 获取国家信息 """
        _language_code = request.lang
        country_rcds = request.env['res.country'].with_context({'lang': _language_code}).sudo().search_read(domain=[],
                                                                                                            fields=['id', 'name', 'code'])
        data = country_rcds
        return valid_response(data)

    @exception_handler
    @validate_rp_api(schema=request_schema_json.get_postal_code_by_country)
    @http.route(route='/api/common/get_postal_code_by_country', auth='none', method=['GET'], cors="*", csrf=False)
    def get_postal_code_by_country(self, **kwargs):
        """ 通过国家获取邮编 """
        _country_id = kwargs.get('country_id')
        _country_code = kwargs.get('country_code').upper()
        _search_name = kwargs.get('search_name')
        country = request.env['res.country'].sudo().search([('id', '=', _country_id)])
        if country.code.upper() != _country_code:
            return invalid_business({}, message_code=1005)
        rp_get = RP_Get(kwargs.get('page', 1), kwargs.get('limit', 10))
        # 先在本地寻找
        postal_code_rcds = request.env['rp.postal.code'].sudo().search([('country_id', '=', _country_id), ('name', 'like', _search_name)], offset=rp_get.offset, limit=rp_get.limit)
        if postal_code_rcds:
            data = [i.printf_for_api() for i in postal_code_rcds]
            return valid_response(data)
        else:
            # 本地邮编不够，去友商packlink获取
            _call_packlink = request.env['rp.backdoor.tran']
            response_dict = _call_packlink._call_packlink_connector(_search_name, _country_code)
            #
            data = []
            for rd in response_dict:
                newrcd = _call_packlink._create_postal_code(_country_id, rd['state'], rd['city'], rd['zipcode'])
                data.append(newrcd.printf_for_api())
            return valid_response(data[:rp_get.limit])

    @exception_handler
    @validate_rp_api()
    @http.route(route='/api/common/get_languages_list', auth='none', method=['GET'], cors="*", csrf=False)
    def get_languages_list(self, **kwargs):
        lang_rcds = request.env['res.lang'].sudo().search_read(domain=[('active', '=', True)], fields=['name', 'code'])
        data = lang_rcds
        return valid_response(data)
